/*
	Copyright (C) 2008  Alex Kemp <kemp00@gmail.com>

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#ifndef _TGA_UTIL_H_
#define _TGA_UTIL_H_

#include <stdio.h>


typedef unsigned char byte;

/*/
/*  Thanks:  http://www.organicbit.com/closecombat/formats/tga.html
/*/
typedef struct __attribute__((__packed__))
{
    byte  identsize;          // size of ID field that follows 18 byte header (0 usually)
    byte  colourmaptype;      // type of colour map 0=none, 1=has palette
    byte  imagetype;          // type of image 0=none,1=indexed,2=rgb,3=grey,+8=rle packed

    short colourmapstart;     // first colour map entry in palette
    short colourmaplength;    // number of colours in palette
    byte  colourmapbits;      // number of bits per palette entry 15,16,24,32

    short xstart;             // image x origin
    short ystart;             // image y origin
    short width;              // image width in pixels
    short height;             // image height in pixels
    byte  bits;               // image bits per pixel 8,16,24,32
    byte  descriptor;         // image descriptor bits (vh flip bits)
    
    // pixel data follows header
    
} TGA_HEADER;

static TGA_HEADER _tga_util_header =
{
	/* identsize = */ 0,
	/* colourmaptype = */ 0,
	/* imagetype = */ 2,
	/* colourmapstart = */ 0,
	/* colourmaplength = */ 0,
	/* colourmapbits = */ 0,
	/* xstart = */ 0,
	/* ystart = */ 0,
	/* width = */ 0,
	/* height = */ 0,
	/* bits = */ 16,
	/* descriptor = */ 0x20
};

int __stdcall write_tga_image (char * fn, int w, int h, int bitspp, unsigned char * mem, int silent)
{
    	FILE * f = fopen (fn, "wb");
    	if (f)
    	{
    		int len = w * h * (bitspp / 8);
    		_tga_util_header.width = w;
    		_tga_util_header.height = h;
    		_tga_util_header.bits = bitspp;
    		fwrite (&_tga_util_header, 1, sizeof (_tga_util_header), f);
    		fwrite (mem, 1, len, f);
    		fclose (f);
    		if (!silent)
    		{
    			fprintf (stderr, "wrought %s\n", fn);
    			fflush (stderr);
    		}
    		return 1;
    	}
    	else
    	{
    		if (!silent)
    		{
	    		fprintf (stderr, "can't open %s\n", fn);
   				fflush (stderr);
   			}
    		return 0;
    	}
}

#endif
